﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace ConsoleApp1.Work6
{
    static class Work61
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }

    public class MainForm : Form
    {
        private MenuStrip menuStrip;
        private ToolStrip toolStrip;
        private SplitContainer splitContainer;
        private TreeView treeView;
        private ListView listView;
        private ImageList imageList;

        public MainForm()
        {
            InitializeComponent();
            LoadRootNodes();
        }

        private void InitializeComponent()
        {
            // Form properties
            this.Text = "简单文件浏览器";
            this.WindowState = FormWindowState.Maximized;

            // MenuStrip
            menuStrip = new MenuStrip();
            var fileMenu = new ToolStripMenuItem("文件");
            fileMenu.DropDownItems.Add("退出", null, (s, e) => this.Close());
            menuStrip.Items.Add(fileMenu);
            this.MainMenuStrip = menuStrip;

            // ToolStrip
            toolStrip = new ToolStrip();
            var btnRefresh = new ToolStripButton("刷新");
            btnRefresh.Click += (s, e) => RefreshCurrentNode();
            toolStrip.Items.Add(btnRefresh);

            // SplitContainer
            splitContainer = new SplitContainer
            {
                Dock = DockStyle.Fill,
                Orientation = Orientation.Vertical,
                SplitterDistance = 250
            };

            // TreeView
            treeView = new TreeView
            {
                Dock = DockStyle.Fill,
                HideSelection = false
            };
            treeView.BeforeExpand += TreeView_BeforeExpand;
            treeView.AfterSelect += TreeView_AfterSelect;

            // ListView
            listView = new ListView
            {
                Dock = DockStyle.Fill,
                View = View.Details,
                FullRowSelect = true
            };
            listView.Columns.Add("名称", 200);
            listView.Columns.Add("类型", 100);
            listView.Columns.Add("大小", 100);
            listView.Columns.Add("修改日期", 150);
            listView.DoubleClick += ListView_DoubleClick;

            // ImageList for icons
            imageList = new ImageList();
            // You can add folder/file icons if desired
            treeView.ImageList = imageList;
            listView.SmallImageList = imageList;

            // Assemble
            splitContainer.Panel1.Controls.Add(treeView);
            splitContainer.Panel2.Controls.Add(listView);

            this.Controls.Add(splitContainer);
            this.Controls.Add(toolStrip);
            this.Controls.Add(menuStrip);
        }

        private void LoadRootNodes()
        {
            treeView.Nodes.Clear();
            // Use user's profile directory as root
            string userPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            var rootNode = CreateDirectoryNode(userPath);
            treeView.Nodes.Add(rootNode);
        }

        private TreeNode CreateDirectoryNode(string path)
        {
            var dirInfo = new DirectoryInfo(path);
            var node = new TreeNode(dirInfo.Name) { Tag = dirInfo.FullName };
            node.Nodes.Add(new TreeNode("...")); 
            return node;
        }

        private void TreeView_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            var node = e.Node;
            node.Nodes.Clear();
            string path = node.Tag as string;
            try
            {
                var dirs = Directory.GetDirectories(path);
                foreach (var dir in dirs)
                    node.Nodes.Add(CreateDirectoryNode(dir));
            }
            catch { /* 权限或其他异常忽略 */ }
        }

        private void TreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            PopulateListView(e.Node.Tag as string);
        }

        private void PopulateListView(string path)
        {
            listView.Items.Clear();
            if (string.IsNullOrEmpty(path)) return;
            try
            {
                var dirInfo = new DirectoryInfo(path);
           
                foreach (var dir in dirInfo.GetDirectories())
                {
                    var item = new ListViewItem(dir.Name);
                    item.SubItems.Add("文件夹");
                    item.SubItems.Add("");
                    item.SubItems.Add(dir.LastWriteTime.ToString());
                    item.Tag = dir.FullName;
                    listView.Items.Add(item);
                }
                // Files
                foreach (var file in dirInfo.GetFiles())
                {
                    var item = new ListViewItem(file.Name);
                    item.SubItems.Add(file.Extension);
                    item.SubItems.Add(file.Length.ToString());
                    item.SubItems.Add(file.LastWriteTime.ToString());
                    item.Tag = file.FullName;
                    listView.Items.Add(item);
                }
            }
            catch { /* 跳过异常 */ }
        }

        private void ListView_DoubleClick(object sender, EventArgs e)
        {
            if (listView.SelectedItems.Count == 0) return;
            var selected = listView.SelectedItems[0];
            var path = selected.Tag as string;
            if (File.Exists(path) && Path.GetExtension(path).Equals(".xml", StringComparison.OrdinalIgnoreCase))
            {
                var viewer = new XmlViewerForm(path);
                viewer.ShowDialog();
            }
            else if (Directory.Exists(path))
            {
                
                SelectTreeNode(path);
            }
        }

        private void SelectTreeNode(string path)
        {
            TreeNode found = FindNodeByPath(treeView.Nodes, path);
            if (found != null)
            {
                treeView.SelectedNode = found;
                found.Expand();
            }
        }

        private TreeNode FindNodeByPath(TreeNodeCollection nodes, string path)
        {
            foreach (TreeNode node in nodes)
            {
                if ((node.Tag as string) == path)
                    return node;
                var child = FindNodeByPath(node.Nodes, path);
                if (child != null) return child;
            }
            return null;
        }

        private void RefreshCurrentNode()
        {
            var node = treeView.SelectedNode ?? treeView.Nodes[0];
            node.Collapse();
            TreeView_BeforeExpand(this, new TreeViewCancelEventArgs(node, false, TreeViewAction.Expand));
            node.Expand();
            PopulateListView(node.Tag as string);
        }
    }

    public class XmlViewerForm : Form
    {
        private TreeView xmlTree;

        public XmlViewerForm(string xmlPath)
        {
            this.Text = "XML 查看 - " + Path.GetFileName(xmlPath);
            this.Width = 600;
            this.Height = 400;

            xmlTree = new TreeView { Dock = DockStyle.Fill };
            this.Controls.Add(xmlTree);

            LoadXml(xmlPath);
        }

        private void LoadXml(string path)
        {
            try
            {
                var doc = XDocument.Load(path);
                xmlTree.Nodes.Clear();
                var rootNode = CreateXmlNode(doc.Root);
                xmlTree.Nodes.Add(rootNode);
                rootNode.Expand();
            }
            catch (Exception ex)
            {
                MessageBox.Show("无法加载 XML: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private TreeNode CreateXmlNode(XElement element)
        {
            var nodeText = element.Name.LocalName;
            if (element.Attributes().Any())
            {
                var attrs = string.Join(" ", element.Attributes().Select(a => $"{a.Name}='{a.Value}'"));
                nodeText += " [" + attrs + "]";
            }
            var node = new TreeNode(nodeText);
            foreach (var child in element.Elements())
                node.Nodes.Add(CreateXmlNode(child));
            if (!string.IsNullOrWhiteSpace(element.Value) && element.Elements().Count() == 0)
            {
                node.Nodes.Add(new TreeNode("#text: " + element.Value));
            }
            return node;
        }
    }
}
